package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 新增支付信息
     * @param userId
     * @param paymentType
     * @param orderNo
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(Long userId, String paymentType, String orderNo) {
        //查询支付信息
        LambdaQueryWrapper<PaymentInfo> paymentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paymentInfoLambdaQueryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(paymentInfoLambdaQueryWrapper);
        if (paymentInfo != null){
            return paymentInfo;
        }

        //新增支付记录
        paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setOutTradeNo(orderNo);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);

        //查询订单信息
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在！");
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(211, "订单状态错误！");
            }
        }else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //远程调用账户服务获取充值金额
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在！");
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
                throw new GuiguException(211, "充值订单状态错误！");
            }
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值" + rechargeInfo.getRechargeAmount());
        }



        this.save(paymentInfo);

        return paymentInfo;
    }

    /**
     * 更新支付信息
     * @param transaction
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentInfoSuccess(Transaction transaction) {
        //获取支付信息
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> paymentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paymentInfoLambdaQueryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(paymentInfoLambdaQueryWrapper);
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
            //如果已支付：返回即可
            return;
        }
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackContent(transaction.toString());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        this.updateById(paymentInfo);

        //修改订单状态
        //消费
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())){
            //修改订单状态
            Result result = orderFeignClient.paySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改订单状态异常：" + orderNo);
            }
        }
        //充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())){
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new GuiguException(500, "远程修改账户状态异常：" + orderNo);
            }
        }



    }
}
